//
//  BSBaseEssenceViewController.m
//  BaiSi
//
//  Created by Sycamore on 16/5/2.
//  Copyright © 2016年 Sycamore. All rights reserved.
//

#import "BSBaseEssenceViewController.h"
#import "BSBaseThemeViewController.h"

@interface BSBaseEssenceViewController () <UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic,weak) UIScrollView *titleMenu;
@property (nonatomic,weak) UICollectionView *contentView;
@property (nonatomic,weak) UIView *lineView;
@property (nonatomic,strong) NSMutableArray *buttonArray;
@property (nonatomic,weak) UIButton *selectedButton;
@property (nonatomic,assign) BOOL isInitial;

@end

@implementation BSBaseEssenceViewController


static NSString * const ID = @"cell";

- (NSMutableArray *)buttonArray
{
    if (!_buttonArray) {
        _buttonArray = [NSMutableArray array];
    }
    return _buttonArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    //创建contentView
    [self setContentView];
    
    //创建titleMenu
    [self setTitleMenu];
    
    
    //设置菜单栏的标题
    [self setAllTitlesInTitleMenu];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //由于该方法可能会调用多次，所以可以给定一个标示，让其只会调用一次
    if (_isInitial == NO) {
        [self setAllTitlesInTitleMenu];
        
        _isInitial = YES;

    }
}

- (void)selectedButton:(UIButton *)button
{
    _selectedButton.selected = NO;
    button.selected = YES;
    _selectedButton = button;
    
    //滑动line
    [UIView animateWithDuration:0.20f animations:^{
        _lineView.bs_centerX = button.bs_centerX;
        
    }];
}

- (void)buttonDidClick:(UIButton *)button
{
    //拿到对应的控制器，让其刷新数据(重复点击某个按钮的时候，才进行刷新)
    if (_selectedButton == button) {
        BSBaseThemeViewController *vc = self.childViewControllers[button.tag];
        [vc loadData];
    }

    //选中响应的按钮
    [self selectedButton:button];
    
    
    
    
    //设置collectionView的偏移，当cel显示的时候，往里面添加view
    _contentView.contentOffset = CGPointMake(BSScreenWidth * button.tag, 0);
    
    
    //添加响应的view
    //collectionView比较特殊，要在每次cell显示的时候将view加上去，而不是滚动完成的时候添加
    
    //此时拿不到cell.cell为空，contentView并不是马上生效的，所以在创建cell的代理方法里面添加view
    //    UITableViewCell *cell = [_contentView cellForItemAtIndexPath:button.tag];
}

//设置菜单栏的标题
- (void)setAllTitlesInTitleMenu
{
    //创建按钮
    NSInteger count = self.childViewControllers.count;
    
    CGFloat buttonWidth = BSScreenWidth / count;
    CGFloat lineHeight = 2.0f;
    CGFloat buttonHeight = _titleMenu.bs_height - lineHeight;
    for (NSInteger index = 0; index < count; index ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(index * buttonWidth, 0, buttonWidth, buttonHeight);
        button.tag = index;
        
        NSString *title = self.childViewControllers[index].title;
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        
        [_titleMenu addSubview:button];
        
        [button addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //将button放进数组里面
        [self.buttonArray addObject:button];
        
        //默认选中第一个按钮
        if (index == 0) {
            [self buttonDidClick:button];
            
            //创建下划线
            UIView *line = [[UIView alloc]init];
            line.backgroundColor = [UIColor redColor];
            //根据文字宽度设置下划线宽度，不能根据button的titleLabel来设置，此时titleLabel的宽度并没有计算出来
            line.bs_width = [button.titleLabel.text sizeWithFont:[UIFont systemFontOfSize:15]].width;
            line.bs_height = lineHeight;
            line.bs_centerX = button.bs_centerX;
            line.bs_Y = _titleMenu.bs_height - line.bs_height;
            
            [_titleMenu addSubview:line];
            _lineView = line;
        }
    }
}


//创建contentView
- (void)setContentView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 0 ;
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(BSScreenWidth, BSScreenHeight);
    
    UICollectionView *contentView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    contentView.dataSource = self;
    contentView.delegate = self;
    contentView.pagingEnabled = YES;
    [self.view addSubview:contentView];
    _contentView = contentView;
    contentView.backgroundColor = [UIColor redColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //注册cell
    [contentView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}

//创建titleMenu
- (void)setTitleMenu
{
    UIScrollView *titleMenu = [[UIScrollView alloc]init];
    CGFloat titleMenuY = self.navigationController.navigationBarHidden ? 20 : 64 ;
    CGFloat titleMenuH = 35;
    titleMenu.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5];
    titleMenu.frame = CGRectMake(0, titleMenuY, BSScreenWidth, titleMenuH);
    [self.view addSubview:titleMenu];
    _titleMenu = titleMenu;
}

- (void)setUpNavigationBar
{
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.image = [UIImage imageNamed:@"MainTitle"];
    [imageView sizeToFit];
    self.navigationItem.titleView = imageView;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"nav_item_game_icon"] highlightedImage:[UIImage imageNamed:@"nav_item_game_click_icon"] target:self action:@selector(leftButtonClick)];
}

- (void)leftButtonClick
{
    BSFunction;
}

#pragma mark UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 5;
}


//每次cell一显示，就会调用此方法，可以在这里面在cell上加上自己想要的view
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    //由于cell的重用问题，上面的view会越来越多,所以需要移除
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview )];
    
    //将相应控制器的view添加到cell上面来
    UIView *view = self.childViewControllers [indexPath.row].view;
    //注意,view的frame一定要设置，不然容易出错
    view.frame = self.view.bounds;
    [cell.contentView addSubview:view];
//    view.backgroundColor = BSColor(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256));
    
    return cell;
}


#pragma mark UICollectionViewDelegate

//滚动完成的时候调用此方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x / BSScreenWidth;
    [self selectedButton:self.buttonArray[page]];
}
@end
